package com.ysu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysu.demo.dataobject.Expend;
import com.ysu.demo.dto.ExpendDTOCollege;
import com.ysu.demo.enums.ExceptionEnum;
import com.ysu.demo.enums.ExpendState;
import com.ysu.demo.exception.BaseException;
import com.ysu.demo.from.expend.ExpendPassForm;
import com.ysu.demo.from.expend.ExpendUploadForm;
import com.ysu.demo.from.expend.MoneyApplyForm;
import com.ysu.demo.mapper.ExpendMapper;
import com.ysu.demo.service.ICollegeService;
import com.ysu.demo.service.IExpendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysu.demo.service.IProjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lhw
 * @since 2019-08-21
 */
@Service
public class ExpendServiceImpl extends ServiceImpl<ExpendMapper, Expend> implements IExpendService {
    @Autowired
    ICollegeService collegeService;

    @Autowired
    IProjectService projectService;

    @Override
    public void passExpend(ExpendPassForm form) {
        Expend newExpend = this.getById(form.getId());

        if(newExpend == null){
            throw new BaseException(ExceptionEnum.NOT_FIND);
        }

        newExpend.setPassUrl(form.getPassUrl());
        newExpend.setState(ExpendState.WAIT_EXPEND.getCode());

        this.updateById(newExpend);
    }

    @Override
    public void uploadExpend(ExpendUploadForm form) {
        Expend newExpend=this.getById(form.getId());

        if(newExpend == null){
            throw new BaseException(ExceptionEnum.NOT_FIND);
        }

        newExpend.setExpendUrl(form.getExpendUrl());
        newExpend.setState(ExpendState.OVER.getCode());

        this.updateById(newExpend);
    }

    @Override
    public List<ExpendDTOCollege> findDTO(Integer projectId) {
        List<Expend> res = this.list(new QueryWrapper<Expend>()
                .eq("project_id",projectId));

        List<ExpendDTOCollege> result = new ArrayList<>();

        for (Expend re : res) {
            ExpendDTOCollege one = new ExpendDTOCollege();

            BeanUtils.copyProperties(re,one);

            one.setCollege(collegeService.getById(re.getCollegeId()));

            result.add(one);
        }

        return result;
    }

    //初版未校验学院id、项目id
    @Override
    public Boolean moneyApply(MoneyApplyForm form) {
        if(projectService.getById(form.getProjectId()) == null ||
            collegeService.getById(form.getCollegeId()) == null){
            throw new BaseException(ExceptionEnum.NOT_FIND);
        }

        Expend expend=new Expend();

        BeanUtils.copyProperties(form,expend);

        expend.setState(ExpendState.WAIT_GOD.getCode());

        return this.save(expend);
    }
}
